package com.eco.fanliapp.admin.controller.web;

import com.alibaba.fastjson.JSON;
import com.eco.fanliapp.admin.annotation.SysLogAnnotation;
import com.eco.fanliapp.admin.common.BaseController;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.entity.AppQny;
import com.eco.fanliapp.entity.BannerPicture;
import com.eco.fanliapp.service.IAppQnyService;
import com.eco.fanliapp.service.IBannerPictureService;
import com.eco.fanliapp.service.RedisTemplateService;
import com.eco.fanliapp.utils.DateFormatUtils;
import com.eco.fanliapp.utils.HttpUtils;
import com.eco.fanliapp.vo.QnyVo;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/web/bannerPicture")
public class BannerPictureController extends BaseController {

    @Autowired
    private IBannerPictureService bannerPictureService ;
    @Autowired
    private IAppQnyService qnyService ;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisTemplateService redisTemplateService;


    @GetMapping("/uploadPic")
    public ServerResponse<Map> uploadPicToQnyMethod(){
        Integer userId = getAuthentication().getUserId();//管理员id
        AppQny qny = qnyService.selectAppQnyById(userId);
        HashMap<String, String> modelMap = new HashMap<>();
        if(qny!=null){
            String accessKey = qny.getAccesskey();
            String secretKey = qny.getSecretkey();
            String bucket = qny.getBucket();
            try{
                String token = (String)redisTemplate.opsForValue().get("qnyUploadToken:"+userId);
                String upToken ="";
                if(StringUtils.isNotEmpty(token)){
                    upToken = token;
                }else{
                    Auth auth = Auth.create(accessKey, secretKey);
                    upToken = auth.uploadToken(bucket);
                    redisTemplate.opsForValue().set("qnyUploadToken:"+userId,upToken,3590, TimeUnit.SECONDS);
                }
                String url =   "https://uc.qbox.me/v1/query?ak="+accessKey+"&bucket="+bucket;
                String  data =   HttpUtils.sendGet(url,"");
                QnyVo qnyq =  new Gson().fromJson(data, QnyVo.class);
                if(qny!=null){
                    modelMap.put("upsite",qnyq.getHttps().getUp().get(0));
                }
                modelMap.put("token",upToken);
                modelMap.put("site",qny.getQnysite());
            }catch (Exception e){
                // ExceptionUtil.errorMsg(BackBannerController.class, e);
            }
        }
        return ServerResponse.createBySuccess("参数获取成功",modelMap);
    }

    @SysLogAnnotation(value = "banner图上传",userType = 2)
    @GetMapping("/picUrl")
    public ServerResponse getPicUrl(String filePath , String upToken) throws QiniuException {

        Configuration cfg = new Configuration(Zone.zone2());
        UploadManager uploadManager = new UploadManager(cfg);
        String[] jsonArray = JSON.parseArray(filePath).toArray(new String[0]);
        AppQny qny = qnyService.selectAppQnyById(1);
        DefaultPutRet putRet = null ;
        ArrayList<String> list = new ArrayList<>();
        for (String filePathStr : jsonArray) {
            long longTime = DateFormatUtils.dateToLong(new Date());
            String fileName = String.valueOf(longTime) ;
            Response response = uploadManager.put(filePathStr,fileName ,upToken);
            // 解析上传成功的结果
            putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
              BannerPicture bannerPicture = new BannerPicture();
              bannerPicture.setMainPictureUrl(qny.getQnysite() + "/" + putRet.key);
            bannerPictureService.insertAndUpdate(bannerPicture);

        }
        return ServerResponse.createBySuccess("上传成功");
    }


    @GetMapping("/findAllBannerPicture")
    public ServerResponse<PageInfo> findAllBannerPicture(@RequestParam(defaultValue = "1") Integer currentPage , @RequestParam(defaultValue = "5") Integer pageSize){
        Integer companyId = getAuthentication().getCompanyId();//管理员id
        return bannerPictureService.findAll(currentPage, pageSize, companyId);

    }

    /**
     * 图片空间 展示列表
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/findAllBanner")
    public ServerResponse<PageInfo> findAllBanner(@RequestParam(defaultValue = "1") Integer currentPage , @RequestParam(defaultValue = "5") Integer pageSize){
        Integer companyId = -1;
        if(getAuthentication().getRoleId() != 0){
            companyId = getAuthentication().getCompanyId();
        }
        return bannerPictureService.findAlls(companyId,currentPage, pageSize);

    }

    @SysLogAnnotation(value = "banner图删除",userType = 2)
    @GetMapping("/delete")
    public ServerResponse fakeDelete(Integer id){
        return bannerPictureService.fakeDelete(id);
    }

    /**
     * 图片添加和修改
     * @param bannerPicture
     * @return
     */
    @SysLogAnnotation(value = "保存banner图",userType = 2)
    @RequestMapping(method = RequestMethod.POST,value = "/save")
    public ServerResponse insertAndUpdate(@RequestBody BannerPicture bannerPicture){
        if(getAuthentication() != null &&getAuthentication().getCompanyId() != null){
            bannerPicture.setCompanyId(getAuthentication().getCompanyId());
        }
        return bannerPictureService.insertAndUpdate(bannerPicture);
    }

    @GetMapping("/poster/height")
    @SysLogAnnotation(value = "banner设置高度",userType = 2)
    public ServerResponse posterHeight(String height){
        String key = "sy_banner_poster_height";
        String redisKeyStr = "app_advertising_h5_onOff";
        if(redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
            redisTemplateService.del(redisKeyStr);
        }
        redisTemplate.opsForValue().set(key,height);
        return  ServerResponse.createBySuccessMessage("高度设置成功");
    }

    @GetMapping("/poster/activityId")
    @SysLogAnnotation(value = "banner设置活动ID",userType = 2)
    public ServerResponse bannerPosterActivityId(String activityId){
        String key = "sy_banner_poster_activityId";
        if(redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
        }
        redisTemplate.opsForValue().set(key,Long.parseLong(activityId));
        return  ServerResponse.createBySuccessMessage("banner设置活动ID");
    }
    @GetMapping("/bannerfree/height")
    @SysLogAnnotation(value = "bannerfree设置高度",userType = 2)
    public ServerResponse bannerFreeHeight(String height){
        String key = "sy_banner_free_height";
        if(redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
        }
        redisTemplate.opsForValue().set(key,height);
        return  ServerResponse.createBySuccessMessage("高度设置成功");
    }

    @GetMapping("/bannerfree/activityId")
    @SysLogAnnotation(value = "bannerfree设置活动ID",userType = 2)
    public ServerResponse bannerFreeActivityId(String activityId){
        String key = "sy_banner_free_activityId";
        if(redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
        }
        redisTemplate.opsForValue().set(key,Long.parseLong(activityId));
        return  ServerResponse.createBySuccessMessage("bannerfree设置活动ID");
    }

    @GetMapping("/elm/activityId")
    @SysLogAnnotation(value = "饿了吗设置活动ID",userType = 2)
    public ServerResponse elmModuleActivityId(String activityId){
        String key = "sy_module_elm_activityId";
        if(redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
        }
        redisTemplate.opsForValue().set(key,Long.parseLong(activityId));
        return  ServerResponse.createBySuccessMessage("饿了吗活动ID设置成功");
    }
}
